package com.jane.fragment.category;


import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jane.adapter.categoryadapter.ZBInnerCategoryAdapter;
import com.jane.bean.ZBInnerCategoryBean;
import com.jane.config.NetConfig;
import com.jane.gzzb.HomePageLiveActivity;
import com.jane.gzzb.PlayActivity;
import com.jane.gzzb.R;
import com.jane.view.GridViewWithHeaderAndFooter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 */
public class ZBCategoryFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, AdapterView.OnItemClickListener {
    private String gameName;
    private GridViewWithHeaderAndFooter gridView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private ZBInnerCategoryAdapter adapter;
    private ArrayList<ZBInnerCategoryBean.CommentatorsBean.GameinfoBean> list=new ArrayList<>();
    private String gameNameEncode;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle=getArguments();
        if(bundle!=null){
            gameName=bundle.getString("gameName");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_zbcategory,null);
        initView(view);
        initData();
        setListener();
        return view;
    }

    private void initView(View view) {
        gridView= (GridViewWithHeaderAndFooter) view.findViewById(R.id.gridview_zb_inner_category);
        swipeRefreshLayout= (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout_zb_inner_category);
        swipeRefreshLayout.setColorSchemeColors(Color.parseColor("#3BA9F2"),Color.parseColor("#FFFF26"),Color.parseColor("#FF0000"),Color.parseColor("#FF80C0"));
        adapter=new ZBInnerCategoryAdapter(list,getActivity());
        addHeaderView();
        gridView.setAdapter(adapter);
    }

    private void addHeaderView() {
        //TODO　添加头布局
        View view=View.inflate(getActivity(),R.layout.header_view_inner_category,null);
        TextView tv= (TextView) view.findViewById(R.id.tv_header_view_inner_category);
        tv.setText(gameName);
        gridView.addHeaderView(view);
    }

    private void initData() {
        try {
            gameNameEncode = URLEncoder.encode(gameName,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String path=NetConfig.ZB_INNER_CATEGORY1+gameNameEncode+NetConfig.ZB_INNER_CATEGORY2+gameNameEncode+NetConfig.ZB_INNER_CATEGORY3;
        RequestParams params=new RequestParams(path);
//        Log.e("path",path);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                swipeRefreshLayout.setRefreshing(false);
                try {
                    JSONObject object=new JSONObject(result);
                    JSONObject commentators = object.getJSONObject("commentators");
                    JSONArray gameinfo = commentators.getJSONArray("gameinfo");
                    for (int i = 0; i <gameinfo.length(); i++) {
                        JSONObject jsonObject = gameinfo.getJSONObject(i);
                        ZBInnerCategoryBean.CommentatorsBean.GameinfoBean gameInfo=new ZBInnerCategoryBean.CommentatorsBean.GameinfoBean();
                        String rawcoverimage=jsonObject.optString("rawcoverimage");
                        String viewers=jsonObject.optString("viewers");
                        String name=jsonObject.optString("name");
                        String title=jsonObject.optString("title");
                        String sourcename=jsonObject.optString("sourcename");
                        String commentator=jsonObject.optString("commentator");
                        String url=jsonObject.optString("url");
                        String roomId=jsonObject.optString("roomid");
                        gameInfo.setName(name);
                        gameInfo.setRawcoverimage(rawcoverimage);
                        gameInfo.setViewers(Integer.parseInt(viewers));
                        gameInfo.setTitle(title);
                        gameInfo.setSourcename(sourcename);
                        gameInfo.setCommentator(commentator);
                        gameInfo.setUrl(url);
                        gameInfo.setRoomid(roomId);
                        list.add(gameInfo);
                    }
//                    Log.e("list",list.toString());
                    //TODO 适配器刷新
                    adapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                swipeRefreshLayout.setRefreshing(false);
                Log.e("onError", "onError: ---------------");
            }

            @Override
            public void onCancelled(CancelledException cex) {
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onFinished() {
                swipeRefreshLayout.setRefreshing(false);
                adapter.notifyDataSetChanged();
            }
        });
    }

    private void setListener() {
        swipeRefreshLayout.setOnRefreshListener(this);
        gridView.setOnItemClickListener(this);
    }

    @Override
    public void onRefresh() {
        initData();
    }
    //设置页面跳转,进行播放
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        playWhich(list.get(position).getSourcename(),list.get(position).getRoomid(),list.get(position).getUrl(),list.get(position).getCommentator());
    }

    private void playWhich(String sourcename,String roomid,String url,String commentator){
        //共12平台
        if(sourcename!=null&&roomid!=null&&url!=null&&commentator!=null){
            switch (sourcename){
                case "熊猫":
                case "全民":
                case "斗鱼":
                    Intent intent=new Intent(getActivity(), PlayActivity.class);
                    intent.putExtra("sourcename",sourcename);
                    intent.putExtra("roomid",roomid);
                    startActivity(intent);
                    break;
                default:
                    Intent intent1=new Intent(getActivity(), HomePageLiveActivity.class);
                    intent1.putExtra("url",url);
                    intent1.putExtra("commentator",commentator);
                    startActivity(intent1);
                    break;
            }
        }
    }
}
